import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
import numpy as np
import time
import sys

mnist = input_data.read_data_sets("MNIST_data/")
def KNN(mnist):  
    train_x,train_y = mnist.train.images,mnist.train.labels
    test_x,test_y = mnist.validation.images,mnist.validation.labels
    print("the train size is ",mnist.train.images.shape)
    print("the validation size is ",mnist.validation.images.shape)
    print("the test size is ",mnist.test.images.shape)
    #sys.exit()
    xtr = tf.placeholder(tf.float32,[None,784])
    xte = tf.placeholder(tf.float32,[784])  
    distance = tf.sqrt(tf.reduce_sum(tf.pow(tf.add(xtr,tf.neg(xte)),2),reduction_indices=1))  
    pred = tf.argmin(distance,0)  
    init = tf.global_variables_initializer()  
    sess = tf.Session()
    sess.run(init)
    samples_size,dim=test_x.shape
    right = 0
    _start=time.time()
    print("start pred")
    for i in range(samples_size):
        ansIndex = sess.run(pred,{xtr:train_x,xte:test_x[i,:]})
        if np.argmax(test_y[i]) == np.argmax(train_y[ansIndex]):  
            right += 1.0
    print("the right is %d " % right)
    accracy = float(right)/samples_size
    _end=time_time()
    used=_end-_start
    print("the accracy is %.2f , validation used time %.2f " %(accracy*100,used))
if __name__ == "__main__":
	start=time.time()
	KNN(mnist)
	end=time.time()
	print("total used time is %.2f" % (end-start))